package com.qianchang.microfinance.view.credit.data;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.dm.library.adapter.CommonAdapter;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.google.gson.Gson;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.ContractBean;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.UpLoadContractBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/12 10:03
 */

public class ContractInfoActivity extends BaseActivity {

    private static final String TAG = "ContractInfoActivity";
    private static final int REQUEST_CODE = 101;

    @BindView(R.id.recycler_view_contract)
    RecyclerView recyclerViewContract;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.tv_tips)
    DTextView tvTips;
    private ContractAdapter contractAdapter;
    List<ContractBean> contractList = new ArrayList<>();
    private Gson gson;
    private int status;
    private String title;
    private FindUserBasicInfoBean basicInfoBean;
    private boolean isConfirmlGoing = false;

    private FindUserBasicInfoBean mBasicInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contract);
        ButterKnife.bind(this);
        initView();
        initData();
        gson = new Gson();
    }

    @Override
    protected void initView() {
        super.initView();
        title = getString(R.string.label_info_contract);
        setTitleName(title);
        contractAdapter = new ContractAdapter(this, contractList);
        recyclerViewContract.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewContract.setAdapter(contractAdapter);
    }

    private boolean isConfirml = false;

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (null != bundle) {
            basicInfoBean = (FindUserBasicInfoBean) bundle.getSerializable(ConstantAppInfo.BASIC_INFO_BEAN);
            if (basicInfoBean == null) {
                basicInfoBean = new FindUserBasicInfoBean();
                basicInfoBean.setIsContactInfo(1);
            }
            status = basicInfoBean.getIsContactInfo();
            isConfirml = bundle.getBoolean("isConfirml", false);
            Log.i("wmy","status = "+status+" isConfirml = "+isConfirml);
        }

        updateStatus();

        switch (status) {
            case 0:
                findContractInfo();
                break;
            case 1:
                break;
            default:
                break;
        }   //是否添加联系人，0：是、1：否

//        MyDataStatus.setBtnStatus(status, btnCommit);
//        MyDataStatus.setTipContent(this, status, tvTips, title, null);

        contractList.add(new ContractBean("", "", status, "", false));
        contractList.add(new ContractBean("", "", status, "", false));
        contractList.add(new ContractBean("", "", status, "", false));
        contractAdapter.notifyDataSetChanged();
//        findContractInfo();
        contractAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                ContractBean contractBean = contractList.get(position);
                if (status == MyDataStatus.YTJ) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(AddContractActivity.CONTRACT_BEAN, contractBean);
                    bundle.putInt(ConstantAppInfo.POSITION, position);
                    bundle.putString(ConstantAppInfo.TITLE, getString(R.string.label_contract_info));
                    startActivity(AddContractActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    if (contractBean.isHasData()) {
                        bundle.putString(ConstantAppInfo.TITLE, getString(R.string.label_update_contract));
                    } else {
                        bundle.putString(ConstantAppInfo.TITLE, getString(R.string.label_add_contract));
                    }
                    bundle.putSerializable(AddContractActivity.CONTRACT_BEAN, contractBean);
                    bundle.putInt(ConstantAppInfo.POSITION, position);
                    startActivityForResult(AddContractActivity.class, bundle, REQUEST_CODE);
                }
            }
        });
        contractAdapter.setOnContractDeleteListener(new ContractAdapter.OnContractDeleteListener() {
            @Override
            public void onDelete() {
//                btnCommit.setEnabled(commitAble());
            }
        });

    }

    /**
     * 获取联系人信息
     */
    private void findContractInfo() {
        show();
        HttpParams params = new HttpParams();

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_CONTACT_INFO, params, new RequestCallBack<ArrayList<ContractBean>>() {//SingleResult<ArrayList<ContractBean>>

            @Override
            public void onSuccess(JsonResult<ArrayList<ContractBean>> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    ArrayList<ContractBean> singleResult = response.getObject();
                    if (null != singleResult) {
                        if (singleResult.size() > 0) {
                            contractAdapter.updateAll(singleResult);
                            contractAdapter.notifyDataSetChanged();
//                            btnCommit.setEnabled(commitAble());
                        }
                    }
                } else {
                    ToastUtil.getInstant().show(ContractInfoActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ContractInfoActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                ContractBean contractBean = (ContractBean) data.getSerializableExtra(AddContractActivity.CONTRACT_BEAN);
                int position = data.getIntExtra(ConstantAppInfo.POSITION, -1);
                if (null != contractBean) {
                    contractList.set(position, contractBean);
                    contractAdapter.notifyDataSetChanged();
//                    btnCommit.setEnabled(commitAble());
                }
            }
        }
    }

//    public boolean commitAble() {
//        for (ContractBean contractBean : contractList) {
//            if (TextUtils.isEmpty(contractBean.getcontactPeopleName()) || TextUtils.isEmpty(contractBean.getcontactPeoplePhone())) {
//                return false;
//            }
//        }
//        return true;
//    }

    @OnClick(R.id.btn_commit)
    public void onViewClicked() {
        insertContractInfo();
    }

    private void insertContractInfo() {
        JSONArray contractJA = new JSONArray();
        for (ContractBean contractBean : contractList) {
            if (TextUtils.isEmpty(contractBean.getcontactPeoplePhone())) {
                ToastUtil.getInstant().show(this, "请将三个联系人添加完整！");
                return;
            }
            try {
                UpLoadContractBean upLoadContractBean = new UpLoadContractBean(contractBean.getcontactPeopleName(), contractBean.getcontactPeoplePhone(), Integer.valueOf(contractBean.getcontactRelationship()));// contractBean.getContactAddress(),
                JSONObject jsonObject = new JSONObject(gson.toJson(upLoadContractBean));
                contractJA.put(jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        show();
        DMOKHttpUtils.getInstance().postString(this, DMConstant.ApiURL.INSERT_CONTACT_INFO, contractJA.toString(), new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {

                    /** 2018.1.20 注释掉迪蒙原来代码
                     ToastUtil.getInstant().show(ContractInfoActivity.this, getString(R.string.commit_success));
                     ContractInfoActivity.this.finish();
                     ****/

                    //2018.1.20 新增自己代码
                    if (isConfirml) {
                        ContractInfoActivity.this.finish();
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, mBasicInfoBean);
                        bundle.putBoolean("isConfirml", isConfirmlGoing);
                        startActivity(PhoneAuthActivity.class, bundle, true);
                    }

                } else {
                    ToastUtil.getInstant().show(ContractInfoActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ContractInfoActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    /*
    获取联系人信息
     */
    private void updateStatus() {

        HttpParams params = new HttpParams();
        show();
        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.FIND_USER_BASIC_INFO, params, new RequestCallBack<FindUserBasicInfoBean>() {

            @Override
            public void onSuccess(JsonResult<FindUserBasicInfoBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    mBasicInfoBean = response.getObject();
                } else {
                    mBasicInfoBean = new FindUserBasicInfoBean();
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                mBasicInfoBean = new FindUserBasicInfoBean();
                ToastUtil.getInstant().show(getApplicationContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }

        });
    }


}
